import React, { useEffect, useState } from 'react';
import { TreeSelect, Spin } from 'antd';
import { getCompanyTree } from '@/services/components/userform';

const deepTransform = (data = []) =>
    data.map(({ companyName, id, children = [] }) => ({
        value: id,
        title: companyName,
        key: id,
        children: children.length > 0 ? deepTransform(children) : children
    }));

const SelectCompany = ({ value, onChange, ...restProps }, ref) => {
    const [treeData, setTreeData] = useState([]);
    const [loading, setLoading] = useState(true);

    /* 1、获取公司列表数据 */
    const fetchData = async () => {
        try {
            const response = await getCompanyTree();
            if (response.code === 10000) {
                /* 2、将数据转换为树选择组件所需格式 */
                const finalTreeData = deepTransform(response.data);
                setTreeData(finalTreeData);
            }
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchData();
    }, []);

    return (
        <Spin spinning={loading}>
            <TreeSelect ref={ref} value={value} onChange={onChange} treeData={treeData} {...restProps} />
        </Spin>
    );
};

export default React.forwardRef(SelectCompany);
